package com.rongshu.view.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.RxHelper;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.login.contract.InputAuthCodeView;
import com.rongshu.view.login.entity.PasswordLogin;
import com.rongshu.view.login.entity.VerificationCode;
import com.rongshu.view.login.presenter.InputAuthCodePresenter;
import com.rongshu.view.userInfo.activity.BindPhoneActivity;
import com.rongshu.widget.VerificationCodeView;
import com.utils.SPUtils;
import com.utils.constants.SPKey;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;

import static com.rongshu.utils.UserInfoUtils.getUserId;

/**
 * created by zhengweis on 2019/7/17.
 * description：检验验证码
 * 接受传参：
 * Constant.INTENT_DATA string 手机号码
 * Constant.INTENT_TYPE int 获取验证码类型
 */
public class InputAuthCodeActivity extends BaseActivity<InputAuthCodePresenter> implements InputAuthCodeView {
    @BindView(R.id.head_middle)
    TextView headMiddle;
    @BindView(R.id.txtLoginRequest)
    TextView txtLoginRequest;
    @BindView(R.id.phone_hint)
    TextView phoneHint;
    @BindView(R.id.auth_code)
    VerificationCodeView authCode;
    @BindView(R.id.cut_down_time)
    TextView cutDownTime;
    @BindView(R.id.get_code_hint)
    TextView getCodeHint;
    @BindView(R.id.login_question)
    RelativeLayout login_question;
    @BindView(R.id.top_layout)
    RelativeLayout top_layout;
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    //手机号
    private String phone;
    //获取验证码type
    private int questAuthCodeType;
    //接口返回验证码
    private String netAuthCode;
    //倒计时时间
    private int sumTimes = 0;
    //当前计时
    private int currentTimes = 60;
    //request
    private final int REQUEST_CODE = 0x01;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immersionBar.keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        immersionBar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_input_auth_code;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        phone = intent.getStringExtra(Constant.INTENT_DATA);
        questAuthCodeType = intent.getIntExtra(Constant.INTENT_TYPE, 0);
        sumTimes = intent.getIntExtra(Constant.INTENT_MESSAGE, 0);
        phoneHint.setText("验证码已发送至手机：" + phone);
        netAuthCode = intent.getStringExtra(Constant.INTENT_CODE);
        if (questAuthCodeType == Constant.LOGIN_CODE) {//登录操作
            txtLoginRequest.setVisibility(View.VISIBLE);
            headMiddle.setVisibility(View.GONE);
        } else if (questAuthCodeType == Constant.FIND_PWD) {//找好密码操作
            txtLoginRequest.setVisibility(View.GONE);
            headMiddle.setText("忘记密码");
        } else if (questAuthCodeType == Constant.CHANGE_PWD) {//修改密码
            login_question.setVisibility(View.GONE);
            top_layout.setVisibility(View.VISIBLE);
            txt_top_title.setText("修改密码");
        } else if (questAuthCodeType == Constant.BIND_PHONE) {//绑定手机号码
            login_question.setVisibility(View.GONE);
            top_layout.setVisibility(View.VISIBLE);
            txt_top_title.setText("绑定手机号码");
        } else if (questAuthCodeType == Constant.CHANGE_PHONE) {//更换手机号码
            login_question.setVisibility(View.GONE);
            top_layout.setVisibility(View.VISIBLE);
            txt_top_title.setText("更换手机号码");
        }
        setPresenter(new InputAuthCodePresenter(this), this);
    }

    @Override
    protected void initData() {
        if (sumTimes == 60 || sumTimes <= 1) {
            presenter.getPhoneVerficationCode(phone, questAuthCodeType == Constant.CHANGE_PWD ? Constant.FIND_PWD : questAuthCodeType);
            sumTimes = 60;
        }
        cutDownTime();
        cutDownTime.setClickable(false);
        authCode.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onComplete(String content) {
                if (TextUtils.equals(netAuthCode, content)) {
                    if (questAuthCodeType == Constant.LOGIN_CODE) {//登录操作
                        presenter.getUserRegisterforMobileCode(phone, netAuthCode);
                    } else if (questAuthCodeType == Constant.FIND_PWD || questAuthCodeType == Constant.CHANGE_PWD) {//找好密码操作
                        Intent intent = new Intent(InputAuthCodeActivity.this, ResetPasswordActivity.class);
                        intent.putExtra(Constant.INTENT_MESSAGE, phone);
                        intent.putExtra(Constant.INTENT_DATA, content);
                        intent.putExtra(Constant.INTENT_TYPE, questAuthCodeType);
                        startActivityForResult(intent, REQUEST_CODE);
                    } else if (questAuthCodeType == Constant.BIND_PHONE) {//绑定手机号
                        Map<String, Object> map = new HashMap<>();
                        map.put("user_id", getUserId());
                        map.put("mobile", phone);
                        map.put("sms_code", content);
                        map.put("key", Common.SIGN_KEY);
                        presenter.getBindingMobile((int) map.get("user_id"),
                                (String) map.get("mobile"),
                                (String) map.get("sms_code"),
                                (String) map.get("key"),
                                Common.encryptionSign(map));
                    } else if (questAuthCodeType == Constant.CHANGE_PHONE) {//更换手机号
                        Intent intent = new Intent(InputAuthCodeActivity.this, BindPhoneActivity.class);
                        intent.putExtra(Constant.INTENT_TYPE, Constant.BIND_PHONE);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                } else {
                    toast("验证码有误\n请重新输入");
                }
            }
        });
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                showKeyboard(false);
                if (data != null && data.hasExtra(Constant.INTENT_DATA)) {
                    Intent intent = new Intent();
                    intent.putExtra(Constant.INTENT_DATA, data.getStringExtra(Constant.INTENT_DATA));
                    setResult(RESULT_OK, intent);
                } else {
                    setResult(RESULT_OK);
                }
                finish();
            }
        }
    }

    @OnClick({R.id.layout_close, R.id.layout_back, R.id.txtLoginRequest, R.id.cut_down_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
            case R.id.layout_close:
                onBackPressed();
                break;
            case R.id.txtLoginRequest:
                startActivity(new Intent(this, LoginQuestionActivity.class));
                break;
            case R.id.cut_down_time:
                presenter.getPhoneVerficationCode(phone, questAuthCodeType == Constant.CHANGE_PWD ? Constant.FIND_PWD : questAuthCodeType);
                cutDownTime();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        showKeyboard(false);
        Intent intent = new Intent();
        intent.putExtra(Constant.INTENT_MESSAGE, currentTimes);
        intent.putExtra(Constant.INTENT_CODE, netAuthCode);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onCallBackAuthCode(VerificationCode code) {
        if (code.getErrCode() == 0) {
            toast("验证码已发送");
            netAuthCode = code.getResponse().getSMSCode();
        } else {
            toast(code.getErrMsg());
        }
    }

    @Override
    public void onCallBackLoginSuccess(PasswordLogin passwordLogin) {
        if (passwordLogin.getErrCode() == 0) {
            //保存输入的手机号码
            SPUtils.putPreferences(SPKey.LAST_LOGIN_PHONE, phone);
            //保存userinfo
            PasswordLogin.ResponseBean responseBean = passwordLogin.getResponse();
            UserInfoUtils.saveUserInfo(passwordLogin);
            //笔名
            String biName = responseBean.getBi_name();
            //是否需要修改昵称
            int diyici = responseBean.getDiyici();
            if (diyici == 1) {//未修改笔名
                SetPenNameActivity.toSetPenNameActivity(this, biName, responseBean.getAvatar());
            }
            //记录登录方式
            SPUtils.putPreferences(Constant.LOGIN_WAY, Constant.LOGIN_WAY_PHONE);
            showKeyboard(false);
            setResult(RESULT_OK);
            finish();
        } else {
            toast(passwordLogin.getErrMsg());
        }
    }

    @Override
    public void onBindPhone(INetBean bean) {
        if (bean.getErrCode() == 0) {
            showKeyboard(false);
            Intent intent = new Intent();
            intent.putExtra(Constant.INTENT_DATA, phone);
            //保存输入的手机号码
            SPUtils.putPreferences(SPKey.LAST_LOGIN_PHONE, phone);
            setResult(RESULT_OK, intent);
            finish();
        } else {
            toast(bean.getErrMsg());
        }
    }

    //倒计时操作
    private void cutDownTime() {
        RxHelper.countdown(sumTimes)
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        getCodeHint.setVisibility(View.GONE);
                        cutDownTime.setClickable(true);
                        cutDownTime.setText("重新获取");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        currentTimes = integer;
                        getCodeHint.setVisibility(View.VISIBLE);
                        cutDownTime.setClickable(false);
                        cutDownTime.setText(integer + "s");
                    }
                });
    }
}
